import collections
import math

from histogram.histcoll import HistogramCollection
from histogram.exceptions import HistogramIOError
import histogram.htypes as ht


def dump(hin, path):
    if type(hin) == type(HistogramCollection()):
        hc = hin
    elif type(hin) in ht.htypes:
        hc = HistogramCollection()
        hc.add(hin)
    elif isinstance(hin, collections.Mapping):
        hc = HistogramCollection()
        if '__hmod__' in hin:
            hc.module_name = hin['__hmod__']
        
        for k in hin:
            if k == '__hmod__':
                continue
            hc.append(hin[k])                    

    elif isinstance(hin, collections.Sequence):
        hc = HistogramCollection(hin)
    else:
        msg = "histogram.dump() does not support output of type {0}"
        raise HistogramIOError(msg.format(type(h)))


    with open(path, 'w') as fpout:
        for k, h in enumerate(hc):
            msg = 'id ' + str(k+1)  + '\n'
            msg += 'title ' + h.name + '\n'
            msg += 'order x y dy\n'
            msg += 'data\n'
            for i in xrange(h.nbins):
                msg += '{0:.8e} {1:.8e} {2:.8e}'.format(h.bin_center(i), 
                                                        h._bins[i], 
                                                        math.sqrt(h._bins[i]))
                msg += '\n'
            msg += 'end\n'

        fpout.write(msg)
